﻿// //文档就绪函数
$(function () {
    show();
    DeviceAdd();
})
//工艺添加方法
// 表单提交事件
layui.use(['layer', 'form', 'util', 'table'], function () {
  var layer = layui.layer;
    var $ = layui.jquery;
    var form = layui.form;
    var util = layui.util;
    var table = layui.table;

    // 点击批量删除按钮的事件处理
    $('#CraftDeletees').click(function () {
        var checkStatus = table.checkStatus('carriertable');
        var selectedIds = checkStatus.data.map(function (item) { return item.craftManageId; });
        console.log(selectedIds)
        if (selectedIds.length === 0) {
            layer.msg('请至少选择一条要删除的数据', { icon: 2 });
            return;
        }
        layer.confirm('确定要批量删除选中的 ' + selectedIds.length + ' 条数据吗？', function (index) {
            console.log(selectedIds)
           localStorage.setItem("Token","")
           
            // 发送Ajax请求到后端，传递选中的id数组进行删除操作
            $.ajax({
                url: '/Craft/GetDeleteesCraft', // 后端批量删除接口地址，根据实际调整
                type: 'Post',
                data: {
                    Data: JSON.stringify(selectedIds),
                    Token: localStorage.getItem("Token")
             },
                success: function (res) {
                    var res = JSON.parse(res)
                    console.log(res)
                    if (res.data > 0) {
                        layer.msg('批量删除成功', { icon: 1 });
                        show()
                    } else {
                        layer.msg('批量删除失败：' + res.message, { icon: 2 });
                    }
                    layer.close(index);
                },
                error: function () {
                    layer.msg('请求出错，请稍后再试', { icon: 2 });
                    layer.close(index);
                }
            });
        });
    });
    
    //工艺删除
    window.deleteData = function (id) {
        console.log(id);
        layer.confirm('确定要删除该条数据吗？', function (index) {
            $.ajax({
                type: "Post",
                url: "/Craft/GetDeleteCraft",  // 替换为实际的后台删除数据接口地址
                data: { data: JSON.stringify([id]), token: localStorage.getItem("token") },
                success: function (res) {
                    var res = JSON.parse(res)
                    if (res.data > 0) {
                        layer.alert("删除成功");
                        show();  // 重新加载数据，刷新表格显示
                    } else {
                        layer.alert("删除失败");

                    }
                },
                error: function () {
                    layer.msg('删除失败，请稍后重试', {
                        time: 2000,
                        icon: 2
                    });
                }
            });
            layer.close(index);
        });
    };
    //编辑跳页面
    window.updateData = function (craftManageId) {
        localStorage["craftManageId"] = craftManageId;
        location.href = '/Craft/CraftUpdate'
    }

    //工艺添加方法
    form.on('submit(demo2)', function (data) {
        var field = data.field;
        var checkStatus = table.checkStatus('allocationProduct');
        field.storageProducts = checkStatus.data.map(function (item) {
            return item;
        });
        console.log(field);//field.products
        // 显示填写结果，仅作演示用
        $.ajax({
            url: '/Craft/GetCraftAdd',
            type: 'post',
            data: {
                field: field,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(field);
                console.log(res);
                if (res.code == 0) {
                    layer.alert("添加成功");
                    ////跳转页面
                    setTimeout(function () {
                        location.href = '/Craft/CraftShow'
                    }, 2000);
                } else {
                    layer.alert("添加失败");
                }
            }
        });

        return false; // 阻止默认 form 跳转
    });
});
//工艺显示
function show() {
    layui.use('table', function () {
        var table = layui.table;
        //查询
        var craftManagenumbering = $("#craftManagenumbering").val();
        var craftManageName = $("#craftManageName").val();
        var craftManageState = $("#craftManageState").val();
        $.ajax({
            url: "/Craft/GetCraftShow",
            type: "get",
            data: {
                craftManagenumbering: craftManagenumbering,
                craftManageName: craftManageName,
                craftManageState: craftManageState,
                pageIndex: 1,
                pageSize: 100,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res);
                if (res.code == 0) {
                    console.log(res.data)
                    table.render({
                        elem: '#carriertable',//对应HTML中表格的id
                        data: res.data.plist,//绑定获取的数据
                        //toolbar: '#toolbarDemo',//导出
                        //defaultToolbar: ['exports', 'print'],//导出
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'craftManagenumbering', title: '工艺路线编号', width: 120 },
                            { field: 'craftManageName', title: '工艺路线名称', width: 140 },
                            {
                                field: 'craftManageState', title: '状态', width: 110,
                                templet: function (d) {
                                    if (d.craftManageState == 0) {
                                        return '<span style = "color:green;">启用</span>'
                                    }
                                    else {
                                        return '<span style = "color:red;">禁用</span>'
                                    }
                                }
                            },
                            { field: 'craftManageFinishName', title: '成品名称', width: 110 },
                            { field: 'craftManageDate', title: '创建时间', width: 110 },
                            { field: 'craftManageAddName', title: '添加人', width: 110 },

                            {
                                field: '', title: '操作', templet: function (d) {
                                    return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-edit" onclick="updateData(' + d.craftManageId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                                        '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.craftManageId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="storagemodel(' + d.craftManageId + ')"><i class="layui-icon layui-icon-search"></i>查看</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="storageaudit(' + d.craftManageId + ')"><i class="layui-icon layui-icon-share"></i>审核</a>';
                                }
                            }
                        ]],//<button id="printButton" class="layui-btn layui-btn-normal">打印</button>
                        page: true, // 是否显示分页
                        count: res.data.listcount,
                        limits: [3, 4,5],
                        limit: 3,// 每页默认显示的数量
                        curr: res.data.pagecount,
                    })
                }
                //else {
                //    console.log(res.msg);
                //}
            },
            error: function () {
                console.log("获取数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });


    })
}

/////工序弹框显示
layui.use('layer', function () {
    var $ = layui.$;
    var layer = layui.layer;
    var util = layui.util;
    var form = layui.form;
    var table = layui.table;

    // 打开显示弹窗的按钮点击事件
    util.on('lay-on', {
        'test-page-custom': function () {
            layer.open({
                type: 1,
                title: "添加工序",
                content: `
                    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">工序编号</label>
            <div class="layui-input-inline">
                <input type="text" id="Num" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div>
            <div class="layui-inline" style="margin-left:120px">
                <button type="button" class="layui-btn layui-bg-blue" onclick="Show()">查询</button>
               <button type="button" class="layui-btn layui-bg-blue" onclick="DeviceAdd()">确认选中</button>
            </div>
        </div>
    </div>
    <table class="layui-table" id="PocessProceduresTable" width="100%" ></table>
                    `,
                success: function () {
                    form.render()
                    Show()
                }
                
            });

        }
    })
});
//列表显示
function Show() {
    layui.use(function () {
        var table = layui.table;
        var Num = $("#Num").val();
        var Name = $("#Name").val();
        var status = $("#Status").val();
        console.log(Num)
        // 先进行表格的初始渲染
        table.render({
            elem: '#PocessProceduresTable',  // 表格元素的选择器
            page: {
                limit: 5,
                limits: [5, 8, 10]
            },
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                { field: 'processName', title: '工序名称' },
                { field: 'processNumebring', title: '工序编号' },
                { field: 'processIllustrate', title: '工序说明' },
               
            ]],
            // 初始时可以先不加载数据，等待 ajax 请求成功后再更新
            data: []
        });
        // 创建表格实例
        $.ajax({
            url: "/Craft/ProcessShow",
            type: "get",
            data: {
                pageindex: 1,
                pagesize: 100,
                ProcessNumebring: Num,
                ProcessName: Name,
                ProcessStatus: status
            },
            success: function (data) {
                data = JSON.parse(data);
                console.log(data.data.plist);
                // 在 ajax 请求成功后，使用正确的表格 ID 进行 reload
                table.reload('PocessProceduresTable', {
                    page: {
                        limit: 5,
                        limits: [5, 8, 10]
                    },
                    data: data.data.plist
                });
            },
            error: function () {
                console.log("请求失败");
            }
        });
    });
}

//确认选中
window.DeviceAdd = function DeviceAdd() {
    // 获取选中行的数据（这里主要是获取warehouseId）
    var checkStatus = layui.table.checkStatus('PocessProceduresTable');
    console.log(checkStatus);
    var token = localStorage.getItem("token");
    var ids = [];
    for (i = 0; i < checkStatus.data.length;i++) {
        ids[i] = checkStatus.data[i].processId
    }
    //var ids = checkStatus.data.map(function (item) {
    //    return item.ProcessId;
    //});
    console.log(ids);
    localStorage.setItem("ids"  , ids)
    var idd = ids
    console.log(idd);
    var ss = 0;
    var idsd = idd.map(function (item) {
        ss = item
        return item;

    });
    console.log(ss);
    if (ids.length == 0) {
        layer.msg("请至少选择一条要新增工序的数据");
        return;
    }

    $.ajax({
        type: "get",
        url: "/Craft/ProcessModel",
        data: {
            id: ss,
            token: localStorage.getItem("token")
        },
        success: function (res) {
            var ter = JSON.parse(res)
            console.log(ter.data)
            localStorage.setItem("data", ter.data)
            
            $(ter.data).each(function () {
                localStorage.setItem("data1", this.processNumebring)
                console.log(localStorage.getItem("data1"))
                $('#Proc').val(this.processNumebring);
                $('#ProcessNe1').val(this.processName);
                $('#ProcessIstrate1').val(this.processIllustrate);
            })
        },
    });
   
}












